<!-- 相册编辑弹窗 -->
<template>
  <ele-modal
    :width="460"
    :visible="visible"
    :confirm-loading="loading"
    :title="isUpdate ? '修改图片' : '新建图片'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 5, sm: 5, xs: 24 } : { flex: '90px' }"
      :wrapper-col="
        styleResponsive ? { md: 19, sm: 19, xs: 24 } : { flex: '1' }
      "
    >
      <a-form-item label="图片名称" name="name">
        <a-input
          allow-clear
          :maxlength="20"
          placeholder="请输入图片名称"
          v-model:value="form.name"
        />
      </a-form-item>
      <a-form-item label="图片" name="img">
        <ele-image-upload
          v-model:value="images"
          :limit="1"
          style="width: 5rem; height: 8rem"
          @upload="onUpload"
          :item-style="{ width: '5rem', height: '8rem' }"
          :remove-handler="onRemove"
        />
      </a-form-item>
      <a-form-item label="页码" name="sort">
        <a-input-number
          :min="0"
          :max="99999"
          class="ele-fluid"
          placeholder="请输入页码"
          v-model:value="form.sort"
        />
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue/es';
  import type { FormInstance, Rule } from 'ant-design-vue/es/form';
  import { storeToRefs } from 'pinia';
  import { useThemeStore } from '@/store/modules/theme';
  import useFormData from '@/utils/use-form-data';
  import { addAlbumPage, updateAlbumPage } from '@/api/albumPage';
  import { uploadFile, removeFile } from '@/api/system/file';
  import type { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { API_BASE_URL } from '@/config/setting';
  import { EleImageUpload, EleModal, messageLoading } from 'ele-admin-pro/es';
  import { AlbumPage } from '@/api/albumPage/model';
  import { FileResultData } from '@/api/system/file/model';

  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  // 已上传数据, 可赋初始值用于回显
  const images = ref<ItemType[]>([]);

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: AlbumPage | null;
    //
    albumId: string;
  }>();

  //
  const formRef = ref<FormInstance | null>(null);

  // 是否选择了图片
  const isImages = ref(false);

  // 是否是修改
  const isUpdate = ref(false);

  // 提交状态
  const loading = ref(false);

  //相对地址
  const relativeUrl = ref();

  // 表单数据
  const { form, resetFields, assignFields } = useFormData<AlbumPage>({
    id: undefined,
    albumId: '',
    name: '',
    img: '',
    imgThumbnail: '',
    sort: 1
  });

  // 表单验证规则
  const rules = reactive<Record<string, Rule[]>>({
    name: [
      {
        required: true,
        message: '请输入图片名称',
        type: 'string',
        trigger: 'blur'
      }
    ],
    sort: [
      {
        required: true,
        message: '请输入页码',
        type: 'number',
        trigger: 'blur'
      }
    ]
  });

  /* 保存编辑 */
  const save = () => {
    let imageData: FileResultData;
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(async () => {
        //是否上传封面
        if (images.value.length > 0 && isImages.value) {
          imageData = await uploadFile(
            images.value[0]?.file,
            images.value[0].url
          );
          form.img = imageData.img;
          form.imgThumbnail = imageData.thumbnail;
          console.log('==imageData===' + JSON.stringify(imageData));
        }
        form.albumId = props.albumId;
        loading.value = true;
        const saveOrUpdate = isUpdate.value ? updateAlbumPage : addAlbumPage;
        saveOrUpdate(form)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  const onUpload = (d: ItemType) => {
    console.log('==ItemType====' + JSON.stringify(d));
    isImages.value = true;
  };
  //删除图片
  const onRemove = (item) => {
    if (isUpdate.value && images.value.length > 0) {
      isImages.value = true;
      console.log('==ItemType====' + JSON.stringify(item));
      const hide = messageLoading('请求中..', 0);
      removeFile(relativeUrl.value)
        .then(() => {
          hide();
          images.value = [];
        })
        .catch((e) => {
          hide();
          message.error(e.message);
        });
    } else {
      images.value = [];
    }
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          assignFields({
            ...props.data
          });
          isUpdate.value = true;
          isImages.value = false;
          relativeUrl.value = props.data.img;
          images.value.push({
            uid: '',
            url: API_BASE_URL + 'img?name=' + props.data.img
          });
        } else {
          isUpdate.value = false;
        }
      } else {
        images.value = [];
        resetFields();
        formRef.value?.clearValidate();
      }
    }
  );
</script>
